<?php

/**
 * 消费者(用户模型实体)
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 6/25/16
 * Time: 15:25
 */

namespace Home\Model;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Home\Model\FinishModel;
use Think\Log;
use Think\Model;

class CustomerBillModel extends Model {

    /**
     * 是否存在账单
     * @param $customerId
     * @param int $type  还款类型 1：次月还款，2：分期还款
     * @return bool
     */
    public function hasRecord($customerId, $type = Constant::PAY_TYPE_NEXT_MONTH) {
        if (is_numeric($customerId)) {
            $billDate = $this->billDate();
            $bill = $this->where(['customer_id'=>$customerId, 'type'=>$type, 'bill_date'=>$billDate])->find();
            if ($bill){
                return true;
            }
        }
        return false;
    }

    /**
     * 更新待还金额
     * @param $customerId
     * @param $amount
     * @param int $type 还款类型 1：次月还款，2：分期还款
     * @return bool
     */
    public function updateRepaymentAmount($customerId, $amount, $billDate, $type = Constant::PAY_TYPE_NEXT_MONTH)
    {
        Log::write("[".ACTION_NAME."][updateRepaymentAmount]:start", Log::INFO);
        $res = true;
        if (is_numeric($customerId) && is_numeric($amount)) {
            $data = ['customer_id'=>$customerId, 'type'=>$type, 'bill_date'=>$billDate];
            $chk = $this->where($data)->find();
            if($chk){
                $sql = "UPDATE customer_bill 
                      SET repayment_amount = repayment_amount+".$amount." 
                    WHERE customer_id = ".$customerId."
                      AND type = ".$type."
                      AND bill_date = '".$billDate."'";
                Log::write("sql=".sql, Log::DEBUG);
                $res = $this->execute($sql);
            }

            Log::write("[".ACTION_NAME."][updateRepaymentAmount]:end", Log::INFO);
            return $res;
        }
        return false;
    }

    /**
     * 本月消费的记录只能在下月的1号后才能看到，所以账单日期是下个月
     * 账单日期
     * @return bool|string
     */
    public function billDate()
    {
        return date("Y-m", strtotime("+1month"));
    }

    /**
     * 计算分期本金和利息,单位分
     * @param int $amount
     * @return array
     */
    public function getInstallmentDetail( $amount, $repayTimes = Constant::REPAY_TIMES, $rate = Constant::INTEREST_RATE )
    {
        $principal = ceil($amount / $repayTimes);
        $interest = ceil($amount * $rate);
        $bill = ceil(($principal + $interest)/100)*100;
        return ['principal'=>$principal, 'interest'=>$interest, 'bill'=>$bill];
    }

    /*************************************************************************
     * 功能描述：用户账单数据
     * 创建时间：2016-8-14
     *************************************************************************/
    public function insCustomerBillDetail($consume, $config=NULL, $repay_diff_cur_month=1)
    {
        Log::write("[".ACTION_NAME."][insCustomerBillDetail]:start", Log::INFO);

        //分期还款方式
        $cut_interest = 0;
        if($consume['type'] == Constant::PAY_TYPE_INSTALLMENT || $consume['type'] == Constant::PAY_TYPE_WITHDRAWAL){
            // $i 一定要从1开始(原因:账单下月才开始还)
            $repayTimes = isset($config['repay_times']) ? $config['repay_times']:Constant::REPAY_TIMES;
        }
        //次月还款方式
        else if($consume['type'] == Constant::PAY_TYPE_NEXT_MONTH){
            $repayTimes = 1;
        }else{
            Log::write("录入账单数据类型出错：type=".$consume['type'], Log::ERR);
            return false;
        }

        $realAmount = D('Finish')->getWithdrawalDetail($consume['amount'], $config, $config['repay_unit']);

        for ($i = $repay_diff_cur_month; $i < $repayTimes+$repay_diff_cur_month; $i++) {
            $bill_date = (isset($config['timer'])&&$config['timer']>0) ? date('Y-m', add_days($config['timer']*$i-1)) : date('Y-m', get_repayment_date($i));
            $sql = "INSERT INTO customer_bill (
                          customer_id,
                          type,
                          repayment_amount,
                          bill_date,
                          add_time
                        ) VALUES(
                          ".$consume['customer_id'].",
                          ".$consume['type'].",
                          ".$realAmount['bill'].",
                          '".$bill_date."',
                          ".time()."
                        ) ON DUPLICATE KEY UPDATE repayment_amount = repayment_amount + ".$realAmount['bill'];
            Log::write("录入账单数据customer_bill出错,返回结果：,sql=".$sql, Log::ERR);
            if(!($res = $this->execute($sql))){
                Log::write("录入账单数据customer_bill出错,返回结果：res=".$res.",sql=".$sql, Log::ERR);
                return false;
            }
        }

        Log::write("[insCustomerBillDetail]:return=>".json_encode($res), Log::INFO);
        Log::write("[".ACTION_NAME."][insCustomerBillDetail]:end\n", Log::INFO);

        return $res;
    }
}
